import StringUtils from './mod.string';
import Storage from '../mod/storage';
import Http from './mod.http';

export default {
  kEvents: {
    // [Neo] TODO add new event here...
    back: 'back',
    updateHome: 'update.home',
    updatePreClose: 'update.preClose',
    updatePopoverIsShow: 'update.popoverIsShow',
    updateAlertIsShow: 'update.alertIsShow',
    ckeditor_add: 'update.ckeditor_add',

    updateLandList: 'update.updateLandList',
    updateLoanList: 'update.updateLoanList',
    updateMediationList: 'update.updateMediationList',
    updateArbitrationList: 'update.updateArbitrationList',
    updateArbitrationAddList: 'update.updateArbitrationAddList',
    updateStoryList: 'update.updateStoryList',
    updateStoryDetail: 'update.updateStoryDetail',

  },
  template: {
    induction: 1,
  },

  load: function (context, url, data, options) {
    let routerObj = context.$f7router;
    let loadUrl = url + '?data=' + JSON.stringify(data);
    if (routerObj != undefined && routerObj != null && routerObj != '') {
      context.$f7router.navigate(loadUrl, options);
    } else {
      context.$f7.views.main.router.navigate(loadUrl, options);
    }
  },
  back: function (context, url, data, options) {
    context.$f7router.back(url + '?data=' + JSON.stringify(data), options);
  },
  getParamData: function (context) {
    let data = context.$f7route.query.data;
    return data ? JSON.parse(data) : {};
  },

  bindEvent: function (context, name, func) {
    context.$root._data._eventBus.$on(name, func);
  },

  onceEvent: function (context, name, func) {
    context.$root._data._eventBus.$once(name, func);
  },

  fireEvent: function (context, name, obj) {
    context.$root._data._eventBus.$emit(name, obj);
  },
  unbindEvent: function (context, name, func) {
    context.$root._data._eventBus.$off(name, func);
  },
  /**
   * 获取一个对象对象的长度
   * @param _obj
   * @returns {number}
   */
  getObjectLength(_obj) {
    let objType = typeof _obj;
    let len = 0;
    switch (objType) {
      case 'string':
        len = _obj.length;
        break;
      case 'object':
        let subLen = 0;
        for (let i in _obj) {
          subLen++;
        }
        len = subLen;
        break;
    }
    return len;
  },
  // 下载文件 微信不能用
  FileDownloader: function (url, name) {
    new FileDownloader({
      url: encodeURI(url),
      filename: name
    })
  },
  // 下载文件
  DownloadFile: function (url, name) {
    try {
      var DownloadFile_a_id = document.getElementById('DownloadFile_a_id')
      DownloadFile_a_id.href = url + '?mp.wexin.qq.com'
      DownloadFile_a_id.download = name
      DownloadFile_a_id.click()
    } catch (e) {

    }
  },
  // 打开文件
  tipDownloadFile: function (url, name) {
    if (url) {
      Storage.sessionRemove('init');
      window.open(url);
    }
  },
  // 获取url中的参数
  GetQueryString: function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
      return unescape(r[2]);
    }
    return null;
  },
  // 设置导航栏标题
  setTitle: function (context, title = '', fun) {
    if (context) {
      if (title) {
        window.document.title = title;
      }
    }
  },
  // 检测返回键
  setBack: function (context, fun) {
    if (context) {
      let pushHistory = function () {
        var state = {
          title: "title",
          url: "#"
        };
        window.history.pushState(state, "title", "#");
      };
      pushHistory();

      window.onpopstate = function () {
        if (fun) {
          fun();
        }
      };
    }
  },
  // 关闭页面
  close_window: function (context) {
    if (context) {
      Storage.sessionRemove('init');
      window.close();
      WeixinJSBridge.call('closeWindow');// 关闭页面
      wx.closeWindow();
    }
  },
  // 最后一层路由，关闭页面
  history_close_window: function (context, fun) {
    if (context) {
      var history = context.$f7.data.history;
      if (history.length <= 1) {
        this.close_window(context);
      } else {
        if (fun) {
          fun();
        }
      }
    }
  },
  // 设置web的标题
  setTitle_web: function (title) {
    if (title) {
      window.document.title = title;
    }
  },
  // 检测微信返回键
  setBack_web: function (fun) {
    pushHistory();

    function pushHistory() {
      var state = {
        title: "title",
        url: "#"
      };
      window.history.pushState(state, "title", "#");
    };
    window.onpopstate = function () {
      if (fun) {
        fun();
      }
    };
  },
  // 微信关闭页面
  close_wechat: function () {
    window.close();
    WeixinJSBridge.call('closeWindow');// 关闭页面
  },
  //腾讯地图坐标转换为百度地图坐标
  tacentToBaiduMap: function (lng, lat) {
    let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    let x = lng;
    let y = lat;
    let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
    let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
    let lngs = z * Math.cos(theta) + 0.0065;
    let lats = z * Math.sin(theta) + 0.006;
    return {
      longitude: lngs,
      latitude: lats
    }
  },
  // 获取后台版本
  getBackendVersion: function (context, fun) {
    if (context) {
      let params = {
        url: Http.kInterfacePath.version,
        data: {},
        type: Http.httpType.get,
        responseData: true,
        success: _successFun,
      };
      Http.ajax(context, params);
      function _successFun(res) {
        var data = res || '';
        if (fun) {
          fun(data)
        }
      }
    } else {
      if (fun) {
        fun()
      }
    }
  },
  /**
   * 时间戳转换，当天返回 hh:mm，一天以前返回 n天前
   * @param timestamp
   * @returns {string}
   */
  toChatFormatTimeDiff: function (timestamp) {
    // 获取时间戳对应的日期时间，格式 yyyy-MM-dd hh:mm:ss
    let lasttime = this.timestampToFormatDatetime(timestamp);
    // 获取当前系统日期时间，格式 yyyy-MM-dd hh:mm:ss
    let curtime = this.getCurDatetime();

    let lastDate = new Date(lasttime.substr(0, 4), lasttime.substr(5, 2) - 1,
      lasttime.substr(8, 2), lasttime.substr(11, 2), lasttime.substr(14, 2),
      lasttime.substr(17, 2));
    let curDate = new Date(curtime.substr(0, 4), curtime.substr(5, 2) - 1,
      curtime.substr(8, 2), curtime.substr(11, 2), curtime.substr(14, 2),
      curtime.substr(17, 2));

    let dateDifference = curDate.getTime() - lastDate.getTime();//时间差的毫秒数
    let days = Math.floor(dateDifference / (24 * 3600 * 1000))//计算出相差天数
    //计算出小时数
    let leave1 = dateDifference % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
    let hours = Math.floor(leave1 / (3600 * 1000));
    //计算相差分钟数
    let leave2 = leave1 % (3600 * 1000);        //计算小时数后剩余的毫秒数
    let minutes = Math.floor(leave2 / (60 * 1000));
    //计算相差秒数
    let leave3 = leave2 % (60 * 1000);      //计算分钟数后剩余的毫秒数
    let seconds = Math.round(leave3 / 1000);
    let retDate = days + "天 " + hours + "小时 " + minutes + "分钟 " + seconds + "秒";

    if (days > 0) {
      retDate = days + '天前'
    } else {
      retDate = lasttime.substr(11, 5);
    }
    // console.log("result date : " + retDate);
    return retDate;
  },
  /**
   * 时间戳转换为 yyyy-MM-dd hh:mm:ss
   * @param timestamp
   * @returns {string}
   */
  timestampToFormatDatetime: function (timestamp) {
    let end = new Date(timestamp);
    let endyear = this.fix(end.getFullYear(), 4);
    let endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    let endday = this.fix(end.getDate(), 2);
    let endhours = this.fix(end.getHours(), 2);
    let endminutes = this.fix(end.getMinutes(), 2);
    let endseconds = this.fix(end.getSeconds(), 2);
    let curtime = endyear + '-' + endmonth + '-' + endday + ' ' + endhours + ':'
      + endminutes + ':' + endseconds;
    return curtime;
  },
  /**
   * 设置数字几位数显示；例console.log(fix(5, 2));输出结果为05
   * @param num
   * @param length
   * @returns {string}
   */
  fix: function (num, length) {
    return ('' + num).length < length ? ((new Array(length + 1)).join('0')
      + num).slice(-length) : '' + num;
  },
  /**
   * 获取当前系统时间并按照一定格式返回
   * @returns {string} format{yyyy-MM-dd HH:mm:ss}
   */
  getCurDatetime: function () {
    let end = new Date();
    let endyear = this.fix(end.getFullYear(), 4);
    let endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    let endday = this.fix(end.getDate(), 2);
    let endhours = this.fix(end.getHours(), 2);
    let endminutes = this.fix(end.getMinutes(), 2);
    let endseconds = this.fix(end.getSeconds(), 2);
    let curtime = endyear + '-' + endmonth + '-' + endday + ' ' + endhours + ':'
      + endminutes + ':' + endseconds;
    return curtime;
  },
  /**
   * 获取当前系统时间并按照一定格式返回
   * @returns {string} format{yyyy-MM-dd}
   */
  getCurDateday: function () {
    let end = new Date();
    let endyear = this.fix(end.getFullYear(), 4);
    let endmonth = this.fix(parseInt(end.getMonth() + 1), 2);
    let endday = this.fix(end.getDate(), 2);
    let curtime = endyear + '-' + endmonth + '-' + endday;
    return curtime;
  },
  computeFileSize: function (size) {
    size = (size / 1024).toFixed(2);//K
    if (size > 1024) {
      size = (size / 1024).toFixed(2);//M
      size = size + 'M';
    } else {
      size = size + 'K';
    }
    return size;
  },
  convertImgToDataURLviaCanvas: function (url, callback, outputFormat) {
    let img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function () {
      let canvas = document.createElement('CANVAS');
      let ctx = canvas.getContext('2d');
      let dataURL;
      canvas.height = this.height;
      canvas.width = this.width;
      ctx.drawImage(this, 0, 0);
      dataURL = canvas.toDataURL(outputFormat);
      //dataURL = canvas.toDataURL('image/jpeg'); //转换图片为dataURL
      callback(dataURL);
      canvas = null;
    };
    img.src = url;
  },
  checkNumber: function (number) {
    //正则：验证数字 大于0
    let reg = /^\+?[1-9][0-9]*$/;
    if (!reg.test(number)) {
      return false;
    } else {
      return true;
    }
  },
  checkMobile: function (phone) {
    //正则：验证电话号码手机号码，包含至今所有号段
    let reg = /^(1[3|4|5|6|7|8|9])[\d]{9}$/;
    if (!reg.test(phone)) {//alert("电话号码格式错误!");obj.value="";obj.focus();
      return false;
    } else {//alert("您的电话号码:"+phone);
      return true;
    }
  },
  UrlEncode: function (str) {
    function str2asc(strstr) {
      return ("0" + strstr.charCodeAt(0).toString(16)).slice(-2);
    }

    function asc2str(ascasc) {
      return StringUtils.fromCharCode(ascasc);
    }

    let ret = "";
    let strSpecial = "!\"#$%&'()*+,/:;<=>?[]^`{|}~%";
    let tt = "";

    for (let i = 0; i < str.length; i++) {
      let chr = str.charAt(i);
      let c = str2asc(chr);
      tt += chr + ":" + c + "n";
      if (parseInt("0x" + c) > 0x7f) {
        ret += "%" + c.slice(0, 2) + "%" + c.slice(-2);
      } else {
        if (chr == " ") {
          ret += "+";
        } else if (strSpecial.indexOf(chr) != -1) {
          ret += "%" + c.toString(16);
        } else {
          ret += chr;
        }
      }
    }
    return ret;
  },
  /**
   * 设置当前页面上拉加载的页宽
   * @param context
   * @param item_height 每个列表项的高度
   * @returns {number}
   */
  setCurrentPageSize: function (context, item_height) {
    let bodyHeight = context.$$('body').height();
    // console.log(' body height : ' + bodyHeight);
    let navHeight = context.$$('.page.page-current .navbar').height();
    navHeight = navHeight ? navHeight : 0;
    let subnavHeight = context.$$(
      '.page.page-current .navbar .subnavbar').height();
    subnavHeight = subnavHeight ? subnavHeight : 0;
    let toolbarHeight = context.$$('.page.page-current .toolbar').height();
    toolbarHeight = toolbarHeight ? toolbarHeight : 0;
    let defaultHeight = parseInt(navHeight) + parseInt(subnavHeight) + parseInt(
      toolbarHeight) + parseInt(item_height) * 10;
    // console.log(' default height : ' + defaultHeight);
    let diffHeight = parseInt(parseInt(bodyHeight) + 50) - defaultHeight;
    // console.log(' difference height : ' + diffHeight);
    if (diffHeight >= 0) {
      let contHeight = bodyHeight - navHeight - subnavHeight - toolbarHeight
        + 50;
      let remainder = contHeight % parseInt(item_height);
      let pageSizeNum = 0;
      if (remainder != 0) {
        pageSizeNum = Math.ceil(contHeight / parseInt(item_height));
      } else {
        pageSizeNum = Math.ceil(contHeight / parseInt(item_height)) + 1;
      }
      return pageSizeNum;
    } else {
      return 10;
    }
  },
  /**
   * 复制 text 文本至粘贴板
   * @param text
   */
  copyTextToClipboard: function (text, _successHandler, _errorHandler) {
    let textArea = document.createElement("textarea");
    textArea.style.position = 'fixed';
    textArea.style.top = 0;
    textArea.style.left = 0;
    textArea.style.width = '2em';
    textArea.style.height = '2em';
    textArea.style.padding = 0;
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';
    textArea.style.background = 'transparent';
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();

    try {
      let isCopySuccess = document.execCommand('copy') ? true : false;
      if (isCopySuccess) {
        if (_successHandler != null) {
          _successHandler();
        }
        // else
        // console.log('复制内容成功！');
      } else {
        if (_errorHandler != null) {
          _errorHandler('复制内容失败！');
        }
        // else
        //   console.log('复制内容失败！');
      }
      // let msg = document.execCommand('copy') ? '成功' : '失败';
      // console.log('复制内容 ' + msg);
    } catch (err) {
      if (_errorHandler != null) {
        _errorHandler('暂不支持复制功能！');
      }
      // else
      //   console.log('暂不支持复制功能！');
      // console.log('不能使用这种方法复制内容');
    }

    document.body.removeChild(textArea);
  },
  /**
   * 判断图片路径的图片是否存在
   * @param imgUrl
   * @returns {boolean}
   */
  checkImageIsExist: function (imgUrl) {
    let xmlHttp;
    if (window.ActiveXObject) {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else if (window.XMLHttpRequest) {
      xmlHttp = new XMLHttpRequest();
    }
    xmlHttp.open("Get", imgUrl, false);
    xmlHttp.send();
    if (xmlHttp.status == 404) {
      return false;
    } else {
      return true;
    }
  },
  /**
   * 判断是否包含 url 链接字符串
   * @param str_url
   * @returns {boolean}
   */
  isHaveUrlAtStr(str_url) {
    let _this = this;
    let strRegex = "((https|http)?://)"
      + "(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
      + "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
      + "|" // 允许IP和DOMAIN（域名）
      + "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.
      + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名
      + "[a-z]{2,6})" // first level domain- .com or .museum
      + "(:[0-9]{1,4})?" // 端口- :80
      + "((/?)|" // a slash isn't required if there is no file name
      + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)";
    let re = new RegExp(strRegex);
    //re.test()
    if (re.test(str_url)) {
      return true;
    } else {
      return false;
    }
  },
  /**
   * 返回字符串中的 url 链接
   * @param str_url
   * @returns {RegExpMatchArray | Promise<any> | Promise<Response> | *}
   */
  getUrlsAtStr: function (str_url) {
    let reg = /(https?|http):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g;
    let url = str_url.match(reg);
    return url;
  },
  replaceUrlToLink(str, tipFunc) {
    let reg = /((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/g;
    //正则替换
    str = str.replace(reg, function (a) {
      //如果包含http ，indexOf方法如果包含返回0,所以加上!
      if (!a.indexOf('http')) {
        return '<a href="' + a + '" target=_blank>' + a + '</a>';
      } else {
        return '<a href="http://' + a + '" target=_blank>' + a + '</a>';
      }
    });
  },
  /**
   * 获取本地存储数据
   * @returns obj
   */
  getLocalStorageData: function () {
    var _this = this;
    var Obj = {};
    var str = localStorage.getItem('localStorageData');
    if (str) {
      Obj = StringUtils.toJson(str);
    }
    if (!Obj.chat) { // 消息
      Obj.chat = [];
    }
    if (!Obj.approval) { // 审批
      Obj.approval = [];
    }
    if (!Obj.task) { // 任务
      Obj.task = [];
    }
    if (!Obj.journal) { // 日志
      Obj.journal = [];
    }
    return Obj;
  },
  // 保存本地存储数据
  setLocalStorageData: function (Obj) {
    var _this = this;
    if (Obj) {
      localStorage.setItem('localStorageData', StringUtils.toStr(Obj));
    }
  },
  // 根据type 更新数据,返回新数组
  update2type: function (Arr, type, data) {
    var _this = this;
    var haveType = false;
    for (var k in Arr) {
      if (!Arr[k]) {
        continue;
      }
      var t = Arr[k].type || '';
      if (type == t) { // 存在就更新
        Arr[k].data = data;
        haveType = true;
        break;
      }
    }
    if (haveType == false) { // 不存在就添加
      var obj = {
        type: type,
        id: -1,
        data: data,
      };
      Arr.push(obj);
    }
    return Arr;
  },
  // 根据type,获取数据obj
  getData2type: function (Arr, type) {
    var _this = this;
    var Obj = {};
    for (var k in Arr) {
      if (!Arr[k]) {
        continue;
      }
      var t = Arr[k].type || '';
      if (type == t) { // 存在
        Obj = Arr[k];
        break;
      }
    }
    return Obj;
  },
  // 根据id 更新数据,返回新数组
  update2id: function (Arr, id, data) {
    var _this = this;
    var haveType = false;
    for (var k in Arr) {
      if (!Arr[k]) {
        continue;
      }
      var i = Arr[k].id || '';
      if (id == i) { // 存在就更新
        Arr[k].data = data;
        haveType = true;
        break;
      }
    }
    if (haveType == false) { // 不存在就添加
      var obj = {
        id: id,
        data: data,
      };
      Arr.push(obj);
    }
    return Arr;
  },
  // 根据id,获取数据obj
  getData2id: function (Arr, id) {
    var _this = this;
    var Obj = {};
    for (var k in Arr) {
      if (!Arr[k]) {
        continue;
      }
      var i = Arr[k].id || '';
      if (id == i) { // 存在
        Obj = Arr[k];
        break;
      }
    }
    return Obj;
  },
  /**
   * 获取某一模块的本地存储
   * @param _module all 获取全部本地数据；对应 module 时，获取对应 module 的本地数据
   * @param _handler 获取成功后处理函数
   */
  getLocalDataByModule(_module, _handler) {
    let localDraftStr = localStorage.getItem('localStorageData');
    localDraftStr = localDraftStr ? localDraftStr : '';
    if (localDraftStr == '') {
      let initLocalObj = {
        chat: [],
        approval: [],
        task: [],
        journal: [],
      };
      localDraftStr = StringUtils.toStr(initLocalObj);
      localStorage.setItem('localStorageData', localDraftStr);
    }
    let localDraftObj = StringUtils.toJson(localDraftStr);
    if (_handler && typeof _handler == "function") {
      let moduleData = null;
      if (_module == 'all') {
        moduleData = localDraftObj;
      } else {
        moduleData = localDraftObj[_module] ? localDraftObj[_module] : [];
      }
      _handler(moduleData);
    }
  },
  /**
   * 更新某一模块的本地存储
   * @param _module all 更新全部本地数据；对应 module 时，更新对应 module 的本地数据
   * @param _data 要保存的数据，数组格式
   */
  updateLocalDataByModule(_module, _data) {
    let _this = this;
    if (_module != 'all') {
      let localDraftStr = localStorage.getItem('localStorageData');
      localDraftStr = localDraftStr ? localDraftStr : '';
      if (localDraftStr != '') {
        let localDraftObj = StringUtils.toJson(localDraftStr);
        let resObj = {};
        for (let i in localDraftObj) {
          let item = localDraftObj[i];
          if (i == _module) {
            item = _data;
          }
          resObj[i] = item;
        }
        localStorage.setItem('localStorageData', StringUtils.toStr(resObj));
      }
    } else {
      localStorage.setItem('localStorageData', StringUtils.toStr(_data));
    }
  },
  checkDataIsExistById(_id, _arr, _handler) {
    let _this = this;
    if (_arr.length > 0) {
      let ids = [];
      for (let i in _arr) {
        if (!_arr[i].id) {
          continue;
        }
        ids.push(_arr[i].id);
      }
      // console.log('+++++++' + JSON.stringify(ids));
      if (ids.indexOf(_id) > -1) {
        // console.log('+++++++indexOf');
        if (_handler && typeof _handler == "function") {
          // console.log('+++++++function');
          _handler(true);
        }
      } else {
        _handler(false);
      }
    } else {
      _handler(false);
    }
  },
  addOrUpdateDataById(_id, _arr, _data) {
    let _this = this;
    let resArr = [];
    _this.checkDataIsExistById(_id, _arr, function (isExisted) {
      if (isExisted) {
        let afterArr = [];
        for (let i in _arr) {
          let item = _arr[i];
          if (!_arr[i].id) {
            continue;
          }
          if (_arr[i].id == _id) {
            item = _data;
          } else {
            item = _arr[i];
          }
          afterArr.push(item);
        }
        resArr = afterArr;
      } else {
        resArr = _arr;
        resArr.push(_data);
      }
    });
    return resArr;
  },
  deleteDataAtArrById(_id, _arr) {
    let _this = this;
    let resArr = [];
    _this.checkDataIsExistById(_id, _arr, function (isExisted) {
      if (isExisted) {
        let afterArr = [];
        for (let i in _arr) {
          let item = _arr[i];
          if (!_arr[i].id) {
            continue;
          }
          if (_arr[i].id != _id) {
            afterArr.push(item);
          }
        }
        resArr = afterArr;
      } else {
        resArr = _arr;
      }
    });
    return resArr;
  },
  getLocalDataById(_id, _arr, _handler) {
    let _this = this;
    _this.checkDataIsExistById(_id, _arr, function (isExist) {
      if (isExist) {
        let resData = null;
        for (let i in _arr) {
          if (!_arr[i].id) {
            continue;
          }
          if (_arr[i].id == _id) {
            resData = _arr[i];
            break;
          }
        }
        if (_handler && typeof _handler == "function") {
          _handler(resData);
        }
      } else {
        if (_handler && typeof _handler == "function") {
          _handler(null);
        }
      }
    });
  },
  /**
   * 增加或更新某个 module 当中对应 id 的数据
   * @param _module
   * @param _id
   * @param _data
   */
  updateLocalDataByModuleAndId(_module, _id, _data) {
    let _this = this;
    _this.getLocalDataByModule(_module, function (moduleArr) {
      let afterModuleData = _this.addOrUpdateDataById(_id, moduleArr, _data);
      _this.updateLocalDataByModule(_module, afterModuleData);
    });
  },
  /**
   * 删除某个 module 当中对应 id 的数据
   * @param _module
   * @param _id
   * @param _data
   */
  deleteLocalDataByModuleAndId(_module, _id) {
    let _this = this;
    _this.getLocalDataByModule(_module, function (moduleArr) {
      let afterModuleData = _this.deleteDataAtArrById(_id, moduleArr);
      _this.updateLocalDataByModule(_module, afterModuleData);
    });
  },
  /**
   * 获取某个 module 当中对应 id 的数据
   * @param _module
   * @param _id
   * @param _handler
   */
  getLocalDataByModuleAndId(_module, _id, _handler) {
    let _this = this;
    _this.getLocalDataByModule(_module, function (moduleData) {
      _this.getLocalDataById(_id, moduleData, function (data) {
        if (data != null) {
          if (_handler && typeof _handler == "function") {
            _handler(data);
          }
        }
      });
    });
  },
  /**
   * 判断元素id是否存在于arr数组中，存在返回true，不存在返回false
   * @param arr
   * @param id
   * @returns {boolean}
   */
  idInArray: function (id, arr) {
    var _this = this
    var len = arr.length
    var total = 0
    for (var i = 0; i < len; i++) {
      if (arr[i].id == id) {
        total = parseInt(total) + 1
        break
      }
    }
    return (parseInt(total) > 0) ? true : false
  },
  // 删除数组中的值
  delArrayVal: function (arr, val) {
    arr = arr ? arr : [];
    // 逆向循环
    for (let i = arr.length - 1; i >= 0; i--) {
      if (arr[i] === val) {
        arr.splice(i, 1);
      }
    }
    return arr;
  },
  // 判断是否为数组的第一个
  isArrayFast: function (arr, id) {
    var _this = this;
    var bool = false;
    if (arr && id && arr.length > 0 && arr[0].id == id) {
      bool = true;
    }
    return bool;
  },
  // 判断是否为数组的最后一个
  isArrayLast: function (arr, id) {
    var _this = this;
    var bool = false;
    if (arr && id && arr.length > 0 && arr[arr.length - 1].id == id) {
      bool = true;
    }
    return bool;
  },
  // 获取上一个
  getArrayUp: function (arr, id) {
    var _this = this;
    var obj = null;
    var key = 0;
    if (arr && id && arr.length > 0) {
      for (var i in arr) {
        if (!arr[i]) {
          continue;
        }
        if (arr[i].id == id) {
          key = parseInt(i);
          break;
        }
      }
      if (key > 0) {
        obj = arr[key - 1];
      }
    }
    return obj;
  },
  // 获取下一个
  getArrayDown: function (arr, id) {
    var _this = this;
    var obj = null;
    if (arr && id && arr.length > 0) {
      var key = arr.length;
      for (var i in arr) {
        if (!arr[i]) {
          continue;
        }
        if (arr[i].id == id) {
          key = parseInt(i);
          break;
        }
      }
      if (key < arr.length - 1) {
        obj = arr[key + 1];
      }
    }
    return obj;
  },
  // 打电话
  telephone: function (telephone) {
    var _this = this;
    if (telephone && telephone != '' && telephone != 0) {
      window.location.href = 'tel:' + telephone;
    }
  },
  // 判断是不是数组
  isArrayFn: function (arr) {
    if (typeof Array.isArray === 'function') {
      return Array.isArray(arr)
    } else {
      return Object.prototype.toString.call(arr) === '[object Array]'
    }
  },
  // 判断两个数组是否相等
  toCompareArray: function (arr1, arr2) {
    var _this = this;
    arr1 = _this.isArrayFn(arr1) ? arr1 : [];
    arr2 = _this.isArrayFn(arr2) ? arr2 : [];
    var bool = arr1.sort().toString() == arr2.sort().toString() ? true : false;
    return bool;
  },
  /**
   * 根据后缀名获取下载配置的 mime
   * @param _suffix 文件的后缀名
   * @returns {string}
   */
  getMimeBySuffix: function (_suffix) {
    let mimeObj = {
      'apk': 'application/vnd.android.package-archive',
      '3gp': 'video/3gpp',
      'ai': 'application/postscript',
      'aif': 'audio/x-aiff',
      'aifc': 'audio/x-aiff',
      'aiff': 'audio/x-aiff',
      'asc': 'text/plain',
      'atom': 'application/atom+xml',
      'au': 'audio/basic',
      'avi': 'video/x-msvideo',
      'bcpio': 'application/x-bcpio',
      'bin': 'application/octet-stream',
      'bmp': 'image/bmp',
      'cdf': 'application/x-netcdf',
      'cgm': 'image/cgm',
      'class': 'application/octet-stream',
      'cpio': 'application/x-cpio',
      'cpt': 'application/mac-compactpro',
      'csh': 'application/x-csh',
      'css': 'text/css',
      'dcr': 'application/x-director',
      'dif': 'video/x-dv',
      'dir': 'application/x-director',
      'djv': 'image/vnd.djvu',
      'djvu': 'image/vnd.djvu',
      'dll': 'application/octet-stream',
      'dmg': 'application/octet-stream',
      'dms': 'application/octet-stream',
      'doc': 'application/msword',
      'dtd': 'application/xml-dtd',
      'dv': 'video/x-dv',
      'dvi': 'application/x-dvi',
      'dxr': 'application/x-director',
      'eps': 'application/postscript',
      'etx': 'text/x-setext',
      'exe': 'application/octet-stream',
      'ez': 'application/andrew-inset',
      'flv': 'video/x-flv',
      'gif': 'image/gif',
      'gram': 'application/srgs',
      'grxml': 'application/srgs+xml',
      'gtar': 'application/x-gtar',
      'gz': 'application/x-gzip',
      'hdf': 'application/x-hdf',
      'hqx': 'application/mac-binhex40',
      'htm': 'text/html',
      'html': 'text/html',
      'ice': 'x-conference/x-cooltalk',
      'ico': 'image/x-icon',
      'ics': 'text/calendar',
      'ief': 'image/ief',
      'ifb': 'text/calendar',
      'iges': 'model/iges',
      'igs': 'model/iges',
      'jnlp': 'application/x-java-jnlp-file',
      'jp2': 'image/jp2',
      'jpe': 'image/jpeg',
      'jpeg': 'image/jpeg',
      'jpg': 'image/jpeg',
      'js': 'application/x-javascript',
      'kar': 'audio/midi',
      'latex': 'application/x-latex',
      'lha': 'application/octet-stream',
      'lzh': 'application/octet-stream',
      'm3u': 'audio/x-mpegurl',
      'm4a': 'audio/mp4a-latm',
      'm4p': 'audio/mp4a-latm',
      'm4u': 'video/vnd.mpegurl',
      'm4v': 'video/x-m4v',
      'mac': 'image/x-macpaint',
      'man': 'application/x-troff-man',
      'mathml': 'application/mathml+xml',
      'me': 'application/x-troff-me',
      'mesh': 'model/mesh',
      'mid': 'audio/midi',
      'midi': 'audio/midi',
      'mif': 'application/vnd.mif',
      'mov': 'video/quicktime',
      'movie': 'video/x-sgi-movie',
      'mp2': 'audio/mpeg',
      'mp3': 'audio/mpeg',
      'mp4': 'video/mp4',
      'mpe': 'video/mpeg',
      'mpeg': 'video/mpeg',
      'mpg': 'video/mpeg',
      'mpga': 'audio/mpeg',
      'ms': 'application/x-troff-ms',
      'msh': 'model/mesh',
      'mxu': 'video/vnd.mpegurl',
      'nc': 'application/x-netcdf',
      'oda': 'application/oda',
      'ogg': 'application/ogg',
      'ogv': 'video/ogv',
      'pbm': 'image/x-portable-bitmap',
      'pct': 'image/pict',
      'pdb': 'chemical/x-pdb',
      'pdf': 'application/pdf',
      'pgm': 'image/x-portable-graymap',
      'pgn': 'application/x-chess-pgn',
      'pic': 'image/pict',
      'pict': 'image/pict',
      'png': 'image/png',
      'pnm': 'image/x-portable-anymap',
      'pnt': 'image/x-macpaint',
      'pntg': 'image/x-macpaint',
      'ppm': 'image/x-portable-pixmap',
      'ppt': 'application/vnd.ms-powerpoint',
      'ps': 'application/postscript',
      'qt': 'video/quicktime',
      'qti': 'image/x-quicktime',
      'qtif': 'image/x-quicktime',
      'ra': 'audio/x-pn-realaudio',
      'ram': 'audio/x-pn-realaudio',
      'ras': 'image/x-cmu-raster',
      'rdf': 'application/rdf+xml',
      'rgb': 'image/x-rgb',
      'rm': 'application/vnd.rn-realmedia',
      'roff': 'application/x-troff',
      'rtf': 'text/rtf',
      'rtx': 'text/richtext',
      'sgm': 'text/sgml',
      'sgml': 'text/sgml',
      'sh': 'application/x-sh',
      'shar': 'application/x-shar',
      'silo': 'model/mesh',
      'sit': 'application/x-stuffit',
      'skd': 'application/x-koan',
      'skm': 'application/x-koan',
      'skp': 'application/x-koan',
      'skt': 'application/x-koan',
      'smi': 'application/smil',
      'smil': 'application/smil',
      'snd': 'audio/basic',
      'so': 'application/octet-stream',
      'spl': 'application/x-futuresplash',
      'src': 'application/x-wais-source',
      'sv4cpio': 'application/x-sv4cpio',
      'sv4crc': 'application/x-sv4crc',
      'svg': 'image/svg+xml',
      'swf': 'application/x-shockwave-flash',
      't': 'application/x-troff',
      'tar': 'application/x-tar',
      'tcl': 'application/x-tcl',
      'tex': 'application/x-tex',
      'texi': 'application/x-texinfo',
      'texinfo': 'application/x-texinfo',
      'tif': 'image/tiff',
      'tiff': 'image/tiff',
      'tr': 'application/x-troff',
      'tsv': 'text/tab-separated-values',
      'txt': 'text/plain',
      'ustar': 'application/x-ustar',
      'vcd': 'application/x-cdlink',
      'vrml': 'model/vrml',
      'vxml': 'application/voicexml+xml',
      'wav': 'audio/x-wav',
      'wbmp': 'image/vnd.wap.wbmp',
      'wbxml': 'application/vnd.wap.wbxml',
      'webm': 'video/webm',
      'wml': 'text/vnd.wap.wml',
      'wmlc': 'application/vnd.wap.wmlc',
      'wmls': 'text/vnd.wap.wmlscript',
      'wmlsc': 'application/vnd.wap.wmlscriptc',
      'wmv': 'video/x-ms-wmv',
      'wrl': 'model/vrml',
      'xbm': 'image/x-xbitmap',
      'xht': 'application/xhtml+xml',
      'xhtml': 'application/xhtml+xml',
      'xls': 'application/vnd.ms-excel',
      'xml': 'application/xml',
      'xpm': 'image/x-xpixmap',
      'xsl': 'application/xml',
      'xslt': 'application/xslt+xml',
      'xul': 'application/vnd.mozilla.xul+xml',
      'xwd': 'image/x-xwindowdump',
      'xyz': 'chemical/x-xyz',
      'zip': 'application/zip'
    };
    let res = mimeObj[_suffix] ? mimeObj[_suffix] : '';
    return res;
  },
}
